<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { musicManageAPI } from "@/services/song";
import IconSearch from "@/assets/icons/IconSearch.vue";
import { debounce } from "lodash-es";
import { ElMessage, ElMessageBox } from "element-plus";

interface MusicVO {
  id: number;
  musicId: string;
  musicCoverUrl: string | null;
  musicName: string;
  musicAuthor: string;
  musicAlbum: string | null;
  musicPublisDate: string | null;
  musicPushDate: string | null;
  musicLength: string | null;
  musicAverageGrade: string | null;
  musicTypeId: number;
  musicUrl: string | null;
  status: string;
  lyric: string | null;
}
const musicTypeList = ref<{ id: number; typeName: string }[]>([]);
const musicTypeMap = computed(() =>
  Object.fromEntries(
    musicTypeList.value.map((item) => [item.id, item.typeName])
  )
);

const musicData = ref<MusicVO[]>([]);
const query = ref({
  name: "",
});
const size = ref("15");
const options = [
  { value: "15", label: "15" },
  { value: "20", label: "20" },
  { value: "30", label: "30" },
  { value: "40", label: "40" },
  { value: "50", label: "50" },
];

const currentPage = ref(1);
const total = ref(0);
const loading = ref(false);

// Dialog controls
const showDetailDialog = ref(false);
const showAddDialog = ref(false);
const currentDetailData = ref<MusicVO | null>(null);
const formData = ref<MusicVO>({
  id: 0,
  musicId: "",
  musicCoverUrl: "",
  musicName: "",
  musicAuthor: "",
  musicAlbum: "",
  musicPublisDate: "",
  musicPushDate: "",
  musicLength: "",
  musicAverageGrade: "",
  musicTypeId: 0,
  musicUrl: "",
  status: "",
  lyric: "",
});

// 计算分页后的表格数据
const paginatedTableData = computed(() => {
  return musicData.value;
});

// 处理页码改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getData();
};

// 处理每页显示数量改变
const handleSizeChange = (val: string) => {
  size.value = val;
  currentPage.value = 1;
  getData();
};

const handleViewDetail = (row: MusicVO) => {
  currentDetailData.value = { ...row };
  showDetailDialog.value = true;
};

const handleEdit = (row: MusicVO) => {
  formData.value = { ...row };
  showAddDialog.value = true;
};

const handleAdd = () => {
  formData.value = {
    id: 0,
    musicId: "",
    musicCoverUrl: "",
    musicName: "",
    musicAuthor: "",
    musicAlbum: "",
    musicPublisDate: "",
    musicPushDate: "",
    musicLength: "",
    musicAverageGrade: "",
    musicTypeId: 0,
    musicUrl: "",
    status: "",
    lyric: "",
  };
  showAddDialog.value = true;
};

const handleDelete = async (row: MusicVO) => {
  try {
    await ElMessageBox.confirm("确定要删除该音乐吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    await musicManageAPI().deleteMusic(row);
    ElMessage.success("删除成功");
    getData();
  } catch (error) {
    console.error("删除失败:", error);
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

const submitForm = async () => {
  try {
    if (formData.value.id) {
      // Update existing music
      await musicManageAPI().updateMusic(formData.value);
      ElMessage.success("更新成功");
    } else {
      // Add new music
      await musicManageAPI().addMusic(formData.value);
      ElMessage.success("添加成功");
    }
    showAddDialog.value = false;
    getData();
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 搜索方法
const handleSearch = debounce(() => {
  currentPage.value = 1;
  getData();
}, 500);

// 显示格式化函数
const displayText = (value: string | null) => {
  return value ? value : "未填写";
};

const formatDate = (dateString: string | null) => {
  if (!dateString) return "未设置";
  const date = new Date(dateString);
  return date.toLocaleDateString() + " " + date.toLocaleTimeString();
};

// 格式化时长
const formatDuration = (duration: string | null) => {
  return duration ? duration : "未设置";
};

/** 初始化 **/
onMounted(() => {
  getMusicTypes();
  getData();
});

const getMusicTypes = async () => {
  try {
    const res = await musicManageAPI().getmusicType(); // 假设封装了 API
    musicTypeList.value = res.data.filter((item) => item.typeStatus === "1");
  } catch (e) {
    ElMessage.error("获取歌曲类型失败");
  }
};

// 监听搜索条件变化
watch(
  () => query.value.name,
  () => {
    handleSearch();
  }
);

const getData = async () => {
  try {
    loading.value = true;
    const response = await musicManageAPI().getMusicByName(
      query.value.name,
      currentPage.value,
      parseInt(size.value)
    );

    musicData.value = response.data.items.map((item) => ({
      ...item,
      // 保持原始数据不变，只在显示时处理
      musicCoverUrl: item.musicCoverUrl,
      musicAlbum: item.musicAlbum,
      musicPublisDate: item.musicPublisDate,
      musicPushDate: item.musicPushDate,
      musicLength: item.musicLength,
      musicAverageGrade: item.musicAverageGrade,
      musicUrl: item.musicUrl,
      lyric: item.lyric,
    }));
    total.value = response.data.total;
  } catch (error) {
    console.error("获取音乐数据失败:", error);
    ElMessage.error("获取音乐数据失败");
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <div class="flex h-full gap-6">
    <div
      class="flex-1 bg-white rounded-lg p-4 flex flex-col justify-between min-w-0"
    >
      <div class="flex items-center justify-between gap-8 mb-4 flex-wrap">
        <div class="flex gap-8 flex-wrap">
          <div>
            <el-input
              v-model="query.name"
              class="input-grey"
              style="width: 200px"
              placeholder="搜索音乐名称"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <IconSearch class="w-4 h-4 cursor-pointer" />
              </template>
            </el-input>
          </div>
        </div>
        <!-- <el-button type="primary" @click="handleAdd">
          <span>添加音乐</span>
        </el-button> -->
      </div>

      <el-table
        v-loading="loading"
        :data="paginatedTableData"
        style="width: 100%"
        height="85%"
        header-row-class-name="table-header"
        cell-class-name="table-cell"
      >
        <el-table-column label="封面" align="center" width="120">
          <template #default="{ row }">
            <el-avatar :src="row.musicCoverUrl" v-if="row.musicCoverUrl" />
            <span v-else>未填写</span>
          </template>
        </el-table-column>
        <el-table-column prop="musicName" label="音乐名称" align="center" />
        <el-table-column prop="musicAuthor" label="作者" align="center" />
        <el-table-column label="发布日期" align="center">
          <template #default="{ row }">
            {{ formatDate(row.musicPublisDate) }}
          </template>
        </el-table-column>
        <el-table-column label="上架日期" align="center">
          <template #default="{ row }">
            {{ formatDate(row.musicPushDate) }}
          </template>
        </el-table-column>
        <el-table-column label="时长" align="center">
          <template #default="{ row }">
            {{ formatDuration(row.musicLength) }}
          </template>
        </el-table-column>
        <el-table-column label="类型" align="center">
          <template #default="{ row }">
            {{ musicTypeMap[row.musicTypeId] || "未知类型" }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="{ row }">
            {{ row.status === "1" ? "上架" : "下架" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template #default="scope">
            <div class="flex justify-center gap-6">
              <button
                class="text-[#005F59] text-[15px]"
                @click="handleEdit(scope.row)"
              >
                编辑
              </button>
              <button
                class="text-[#FF2D55] text-[15px]"
                @click="handleDelete(scope.row)"
              >
                删除
              </button>
              <button
                class="text-[#0066CC] text-[15px]"
                @click="handleViewDetail(scope.row)"
              >
                详情
              </button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="h-[36px] flex items-center justify-between mt-6">
        <div>
          <span class="text-[#8a8a8f] text-sm mr-2">每页结果</span>
          <el-select
            v-model="size"
            placeholder="Select"
            style="width: 70px"
            class="input-grey"
            @change="handleSizeChange"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <el-pagination
          background
          class="justify-items-end"
          layout="prev, pager, next"
          :total="total"
          :page-size="parseInt(size)"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <!-- 添加/编辑对话框 -->
  <el-dialog
    v-model="showAddDialog"
    :title="formData.id ? '编辑音乐' : '添加音乐'"
    width="50%"
  >
    <el-form :model="formData" label-width="100px">
      <!-- <el-form-item label="音乐ID" required>
        <el-input v-model="formData.musicId" placeholder="请输入音乐ID" />
      </el-form-item> -->
      <el-form-item label="音乐名称" required>
        <el-input v-model="formData.musicName" placeholder="请输入音乐名称" />
      </el-form-item>
      <el-form-item label="作者">
        <el-input v-model="formData.musicAuthor" placeholder="请输入作者" />
      </el-form-item>
      <el-form-item label="发布日期">
        <el-date-picker
          v-model="formData.musicPublisDate"
          type="datetime"
          placeholder="选择发布日期"
          value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"
        />
      </el-form-item>
      <el-form-item label="上架日期">
        <el-date-picker
          v-model="formData.musicPushDate"
          type="datetime"
          placeholder="选择上架日期"
          value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"
        />
      </el-form-item>
      <el-form-item label="时长">
        <el-input
          v-model="formData.musicLength"
          placeholder="请输入时长 (HH:mm:ss)"
        />
      </el-form-item>
      <el-form-item label="类型" required>
        <el-select v-model="formData.musicTypeId" placeholder="请选择类型">
          <el-option
            v-for="type in musicTypeList"
            :key="type.id"
            :label="type.typeName"
            :value="type.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="formData.status" placeholder="请选择状态">
          <el-option label="上架" value="1" />
          <el-option label="下架" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="封面URL">
        <el-input
          v-model="formData.musicCoverUrl"
          placeholder="请输入封面URL"
        />
      </el-form-item>
      <el-form-item label="音乐URL">
        <el-input v-model="formData.musicUrl" placeholder="请输入音乐URL" />
      </el-form-item>
      <el-form-item label="歌词">
        <el-input
          v-model="formData.lyric"
          type="textarea"
          :rows="6"
          placeholder="请输入歌词"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showAddDialog = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>

  <!-- 详情对话框 -->
  <el-dialog v-model="showDetailDialog" title="音乐详情" width="60%">
    <div v-if="currentDetailData" class="detail-container">
      <div class="detail-row">
        <div class="detail-label">音乐ID:</div>
        <div class="detail-value">{{ currentDetailData.musicId }}</div>
      </div>
      <div class="detail-row">
        <div class="detail-label">音乐名称:</div>
        <div class="detail-value">{{ currentDetailData.musicName }}</div>
      </div>
      <div class="detail-row">
        <div class="detail-label">作者:</div>
        <div class="detail-value">{{ currentDetailData.musicAuthor }}</div>
      </div>
      <div class="detail-row">
        <div class="detail-label">发布日期:</div>
        <div class="detail-value">
          {{ formatDate(currentDetailData.musicPublisDate) }}
        </div>
      </div>
      <div class="detail-row">
        <div class="detail-label">上架日期:</div>
        <div class="detail-value">
          {{ formatDate(currentDetailData.musicPushDate) }}
        </div>
      </div>
      <div class="detail-row">
        <div class="detail-label">时长:</div>
        <div class="detail-value">
          {{ formatDuration(currentDetailData.musicLength) }}
        </div>
      </div>
      <div class="detail-row">
        <div class="detail-label">类型:</div>
        <div class="detail-value">
          {{ musicTypeMap[currentDetailData.musicTypeId] || "未知类型" }}
        </div>
      </div>

      <div class="detail-row">
        <div class="detail-label">状态:</div>
        <div class="detail-value">
          {{ currentDetailData.status === "1" ? "上架" : "下架" }}
        </div>
      </div>
      <div class="detail-row">
        <div class="detail-label">封面:</div>
        <div class="detail-value">
          <el-avatar
            :src="currentDetailData.musicCoverUrl"
            v-if="currentDetailData.musicCoverUrl"
          />
          <span v-else>未填写</span>
        </div>
      </div>
      <div class="detail-row" v-if="currentDetailData.lyric">
        <div class="detail-label">歌词:</div>
        <div class="detail-value lyric-content">
          <pre>{{ currentDetailData.lyric }}</pre>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<style lang="scss">
.icon {
  fill: currentColor;
  width: 20px;
  margin-right: 6px;
}
.input-grey {
  .el-input__wrapper {
    background: #f9f9f9;
    padding-left: 8px;
  }
  .el-select__wrapper {
    background: #f9f9f9;
  }
}
.el-table__header-wrapper {
  border-radius: 6px;
}
.table-header {
  background: #b88b7a !important;
  color: white;
  height: 50px !important;
  font-size: 15px;
  .el-table__cell {
    background: transparent !important;
    font-weight: 500;
  }
}
</style>
